/*	BuildMedic class definition.
 *
*/

#include "BuildMedic.h"

void BuildMedic::Enter()
{
	DEBUG_PRINT("BuildMedic(%p) %s entering\n", this, GetName().c_str());

}

void BuildMedic::Execute()
{
	DEBUG_PRINT("BuildMedic(%p) %s executing\n", this, GetName().c_str());
	std::list<Base*>* bases = BB->GetBases();
	std::list<BWAPI::Unit*>* barracksList;
	BWAPI::Unit* bar = NULL;
	for(std::list<Base*>::iterator base = bases->begin(); base != bases->end(); base++)
	{
		barracksList = (*base)->GetBuildingsByType(BWAPI::UnitTypes::Terran_Barracks);
		if(barracksList)
		{
			for(std::list<BWAPI::Unit*>::iterator it = barracksList->begin(); it != barracksList->end(); it++)
			{
				if (!(*it)->isTraining() && !(*it)->isBeingConstructed())
					bar = *it;
			}
			if (bar) 
			{
				BB->SpendResources(BWAPI::UnitTypes::Terran_Medic);
				bar->train(BWAPI::UnitTypes::Terran_Medic);
			}
		}
	}
	control->FinishWithSuccess();
}

void BuildMedic::Exit()
{
	DEBUG_PRINT("BuildMedic(%p) %s exiting\n", this, GetName().c_str());

}

bool BuildMedic::CheckConditions()
{
	DEBUG_PRINT("BuildMedic(%p) %s checking conditions\n", this, GetName().c_str());
	if(BB->isBuildUnit(BWAPI::UnitTypes::Terran_Medic) )
	{
		std::list<BWAPI::Unit*>* medics = BB->GetUnitsByTypeGeneral(BWAPI::UnitTypes::Terran_Medic);
		std::list<BWAPI::Unit*>* marine = BB->GetUnitsByTypeGeneral(BWAPI::UnitTypes::Terran_Marine);
		if(!medics)
			return true;
		if (marine->size()/3 > medics->size())
		{
			DEBUG_PRINT("BuildMedic(%p) %s checked conditions and has %d minerals to spend\n", this, GetName().c_str(), BB->GetMineralsToSpend());
		
			return true;
		}
	}
	return false;
}